<template>
  <view class="p-4">
    <text class="block mb-2">选择运维区域：</text>
    <uni-data-picker
      placeholder="请选择省市区镇"
      popup-title="选择区域"
      :localdata="areaList"
      :value="selectedValue"
      @change="onChange"
    ></uni-data-picker>

    <view class="mt-3">
      <text>选择结果：{{ selectedText }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      areaList: [
        {
          text: '广东省',
          value: '440000',
          children: [
            {
              text: '广州市',
              value: '440100',
              children: [
                {
                  text: '天河区',
                  value: '440106'
                },
                {
                  text: '越秀区',
                  value: '440104'
                }
              ]
            }
          ]
        },
        {
          text: '湖南省',
          value: '430000',
          children: [
            {
              text: '长沙市',
              value: '430100',
              children: [
                {
                  text: '岳麓区',
                  value: '430104'
                }
              ]
            }
          ]
        }
      ],
      selectedValue: [],
      selectedText: ''
    }
  },
  methods: {
    async onChange(e) {
      const selected = e.detail.value
      this.selectedValue = selected.map(item => item.value)
      this.selectedText = selected.map(item => item.text).join('')

      // 如果选择到了第三级（区），则动态加载镇
      if (selected.length === 3) {
        const district = selected[2]

        // 如果没有 children，就加载镇
        if (!district.children || district.children.length === 0) {
          const towns = await this.getTownsByDistrictId(district.value)

          // 设置第四级
          this.$set(district, 'children', towns.map(item => ({
            text: item.name,
            value: item.code
          })))

          // 强制刷新 picker 数据
          this.areaList = JSON.parse(JSON.stringify(this.areaList))
        }
      }
    },
    // 模拟异步请求镇数据
    getTownsByDistrictId(code) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve([
            { name: 'XX镇', code: code + '01' },
            { name: 'YY镇', code: code + '02' }
          ])
        }, 500)
      })
    }
  }
}
</script>

<style scoped>
.p-4 {
  padding: 16px;
}
.mt-3 {
  margin-top: 12px;
}
</style>
